from datetime import datetime
from src.common.config import config
from src.common.logger import getLogger
from src.agentic.rag.special.MMRRAG import MMRRAG
from src.agentic.agent.AgentTools import AgentTools
from src.agentic.rag.special.BM25RAG import BM25RAG
from src.agentic.config.GraphStore import GraphStore
from src.agentic.rag.special.GraphRAG import GraphRAG
from src.agentic.rag.special.KMeanRAG import KMeanRAG
from src.agentic.config.VectorStore import VectorStore
from src.agentic.rag.special.HybridRAG import HybridRAG
from src.agentic.config.LanguageModel import LanguageModel
from src.agentic.config.EmbeddingModel import EmbeddingModel
from src.modules.memory.service import HistoryRecordService, MemoryDetailService

logger = getLogger()

def invoke_retrieval_special(form):
    start_time = datetime.now().second

    HistoryRecordService.insert_history_memory(form)

    base_url = "http://localhost:11434"
    llm_model = LanguageModel("qwen3:4b", base_url, None)
    llm = llm_model.new_llm_model()

    embedding = EmbeddingModel("bge-m3", base_url).new_embed_model()

    config_dict = config.parse_config_key(["qdrant"])
    collection_prefix = config_dict.get("collection_prefix", "")
    logger.info(f"invoke_retrieval_special collection_prefix: {collection_prefix}")

    vector_store = None
    library_number = form.get("library")
    collection_name = collection_prefix + library_number
    logger.info(f"invoke_retrieval_special collection_name: {collection_name}")
    if library_number:
        vector_store = VectorStore().new_vector_store(embedding, collection_name)

    graph_store = GraphStore()
    graph_store = graph_store.new_graph_store()

    agent_tools = AgentTools()
    tools = agent_tools.get_execute_tools()

    rag_retriever = None
    ragPattern = form.get("pattern")
    logger.info(f"invoke_retrieval_special ragPattern: {ragPattern}")
    if ragPattern == "Graph":
        rag_retriever = GraphRAG(llm, graph_store, collection_name)
    elif ragPattern == "KeyWord":
        rag_retriever = BM25RAG(llm, vector_store, collection_prefix, library_number, 3)
    elif ragPattern == "Hybrid":
        rag_retriever = HybridRAG(llm, vector_store, collection_prefix, library_number, 3)
    elif ragPattern == "KMean":
        rag_retriever = KMeanRAG(llm, embedding, vector_store, collection_prefix, library_number, 3, 3)
    elif ragPattern == "MMR":
        rag_retriever = MMRRAG(llm, embedding, vector_store, collection_prefix, library_number, 0.7, 3)
    retrieve_result = rag_retriever.invoke(form.get("query"))

    MemoryDetailService.insert_memory_detail_ai(form, retrieve_result)

    logger.info(f"invoke_retrieval_special time: {datetime.now().second - start_time} s")
    return retrieve_result
